//
//  XS_BaseMiddleAlertController.swift
//  
//
//  Created by 韩云智 on 2021/10/5.
//

import UIKit
import RxSwift
import RxCocoa
import SnapKit

public enum XS_AlertActionType {
    case cancel
    case sure
    case action(Any)
}

open class XS_BaseMiddleAlertController: XS_BaseViewController {
    open lazy var shouldClose = false
    open lazy var scale: CGFloat = 0.5
    open lazy var actionPS = PublishSubject<(XS_BaseMiddleAlertController, XS_AlertActionType)>()
    open lazy var contentRect: CGRect = view.bounds
    open lazy var contentView: UIView = { [weak self] in
        let contentView = UIView()
        if let `self` = self {
            self.view.addSubview(contentView)
            contentView.snp.makeConstraints {
                $0.size.equalTo(contentRect.size)
                $0.centerX.equalToSuperview().offset(contentRect.origin.x)
                $0.centerY.equalToSuperview().offset(contentRect.origin.y)
            }
        }
        return contentView
    }()
    
    open override func upConfig() {
        modalTransitionStyle = .crossDissolve
        modalPresentationStyle = .overFullScreen
    }
    open override func upView() {
        view.alpha = 0
        view.backgroundColor = UIColor(white: 0, alpha: 0.35)
    }
    
    open override func viewDidAppear(_ animated: Bool) {
        super.viewDidAppear(animated)
        if view.alpha == 0 {
            view.alpha = 1
            open()
        }
    }
    
    open override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
        guard shouldClose, touches.first(where: { [weak self] in $0.view === self?.contentView }) == nil else { return }
        actionPS.onNext((self, XS_AlertActionType.cancel))
    }
    
    /// 打开动画
    open func open() {
        contentView.transform = CGAffineTransform(scaleX: scale, y: scale)
        UIView.animate(withDuration: 0.5, delay: 0, usingSpringWithDamping: 0.7, initialSpringVelocity: 15, options: [.curveEaseInOut], animations: {
            self.contentView.transform = CGAffineTransform(scaleX: 1, y: 1)
            self.view.layoutIfNeeded()
        })
    }
    /// 收起动画
    open func close(completion: (() -> Void)? = nil) {
        UIView.animate(withDuration: 0.25, animations: {
            self.contentView.transform = CGAffineTransform(scaleX: self.scale, y: self.scale)
            self.view.alpha = 0
            self.view.layoutIfNeeded()
        }) { _ in
            self.dismiss(animated: false, completion: completion)
        }
    }
}
